﻿using Google.GData.Extensions.MediaRss;
using Google.GData.YouTube;
using Google.YouTube;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using Tebbee.UI.Client.AdvertiseSer;
using Tebbee.UI.Client.UtilitiesSer;

namespace Tebbee.UI.Client.Controllers
{
    public class AdminAdvController : ApiController
    {
        /// <summary>
        /// service class ref
        /// </summary>
        private readonly AdvertiseSerClient db = new AdvertiseSerClient();
        private readonly UtilitiesClient utilities = new UtilitiesClient();
        /// <summary>
        /// Upload file to server (ads)
        /// </summary>
        /// <returns></returns>
        public HttpResponseMessage PostACF()
        {
            HttpResponseMessage result = null;
            var httpRequest = HttpContext.Current.Request;

            if (httpRequest.Files.Count > 0)
            {
                var docfiles = new List<string>();
                for (int i = 0; i < httpRequest.Files.Count; i++)
                {
                    var postedFile = httpRequest.Files[i];
                    if (postedFile.ContentLength == 0)
                    {
                        continue;
                    }
                    var fileName = DateTime.Now.ToString("ddMMyyyy") + DateTime.Now.Minute + Path.GetFileName(postedFile.FileName);
                    var filePath = Path.Combine(HttpRuntime.AppDomainAppPath, "Advertise/" + fileName);
                    try
                    {
                        postedFile.SaveAs(filePath);
                    }
                    catch (Exception ex)
                    {
                        Console.Write(ex.Message);
                    }
                    docfiles.Add(fileName);
                }

                result = Request.CreateResponse(HttpStatusCode.Created, docfiles);
            }
            else
            {
                result = Request.CreateResponse(HttpStatusCode.BadRequest);
            }

            return result;
        }

        /// <summary>
        /// upload preview img to server
        /// </summary>
        /// <returns></returns>
        public HttpResponseMessage PostPreviewThum()
        {
            HttpResponseMessage result = null;
            var httpRequest = HttpContext.Current.Request;
            var fname = httpRequest.Form["fname"];
            if (httpRequest.Files.Count > 0)
            {
                var docfiles = new List<string>();

                foreach (string file in httpRequest.Files)
                {
                    var postedFile = httpRequest.Files[file];
                    var filePath = Path.Combine(HttpRuntime.AppDomainAppPath, "Advertise/PreviewImgs/" + fname);

                    try
                    {
                        postedFile.SaveAs(filePath);
                    }
                    catch (Exception ex)
                    {
                        Console.Write(ex.Message);
                    }
                    docfiles.Add(filePath);
                }

                result = Request.CreateResponse(HttpStatusCode.Created, docfiles);
            }
            else
            {
                result = Request.CreateResponse(HttpStatusCode.BadRequest);
            }

            return result;
        }

        /// <summary>
        /// create a new advertisement
        /// </summary>
        /// <param name="adv"></param>
        /// <returns></returns>
        public HttpResponseMessage PostAdvertise(AdvertiseUpload adv)
        {
            if (ModelState.IsValid)
            {
                string fileName = String.Format("{0:ddMMyyyy}-AdsDescription-{1}.html", DateTime.Now, adv.Title);
                string path = Path.Combine(HttpRuntime.AppDomainAppPath, "Advertise/html/" + fileName);
                if (utilities.WriteFile(adv.Description, path)) adv.Description = "../Advertise/html/" + fileName;
                else return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
                int id = db.AddNewAdvertise(adv);
                return Request.CreateResponse(HttpStatusCode.Created, id);
            }
            else
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }
        }

        /// <summary>
        /// get list of advertisement
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public IEnumerable<Advertise_List_Result> GetAdvertises(int id)
        {
            var queryString = HttpUtility.ParseQueryString(Request.RequestUri.Query);
            if (id < 1) id = 1;
            id = (id - 1) * 10;
            var tmp = db.ListAdvertising(id, 10, 1, queryString["value"]);
            Parallel.ForEach(tmp, item =>
            {
                var link = String.Empty;
                if (String.IsNullOrEmpty(item.Description))
                {
                    item.Description = "";
                }
                else
                {
                    link = item.Description.Replace("../", "");
                    var path = Path.Combine(HttpRuntime.AppDomainAppPath, link);
                    item.Description = utilities.ReadFile(path);
                }
            });
            return tmp;
        }

        /// <summary>
        /// get all category by ads id
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public IEnumerable<CatMap_GetByAdv_Result> GetCategpriesByAdv(int id)
        {
            var tmp = db.GetCategoriesByAdv(id);
            return tmp;
        }

        /// <summary>
        /// get list of media by ad's id
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public IEnumerable<Media_GetByAdv_Result> GetMediaByAdv(int id)
        {
            var tmp = db.GetMediaByAdv(id);
            return tmp;
        }

        /// <summary>
        /// Delete an advertisement
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public HttpResponseMessage DeleteAdvertise(int id)
        {
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }

            var lst = db.GetDelImg(id);

            if (lst.Any())
            {
                Parallel.ForEach(lst, link =>
                {
                    String delPath = String.Empty;
                    link = link.Replace("../", "");
                    delPath = Path.Combine(HttpRuntime.AppDomainAppPath, link);

                    if (!String.IsNullOrEmpty(delPath))
                    {

                        FileInfo delFile = new FileInfo(delPath);
                        if (delFile.Exists)
                        {
                            File.Delete(delPath);
                        }
                    }
                });
            }

            if (db.DelAdv(id) != 0)
            {
                return Request.CreateResponse(HttpStatusCode.OK, id);
            }
            else
            {
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Not Found");
            }
        }

        /// <summary>
        /// Edit advertisement information
        /// </summary>
        /// <param name="adv"></param>
        /// <returns></returns>
        public HttpResponseMessage PutAdvertise(Advertisement adv)
        {
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }
            string fileName = String.Format("{0:ddMMyyyy}-AdsDescription-{1}.html", DateTime.Now, adv.Title);
            string path = Path.Combine(HttpRuntime.AppDomainAppPath, "Advertise/html/" + fileName);
            if (utilities.WriteFile(adv.Description, path)) adv.Description = "../Advertise/html/" + fileName;
            else return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            if (db.EditAdv(adv) != 0)
            {
                return Request.CreateResponse(HttpStatusCode.OK, adv);
            }
            else
            {
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Not Found");
            }
        }

        /// <summary>
        /// update video link to database. when upload video to youtube
        /// </summary>
        /// <param name="video"></param>
        /// <returns></returns>
        public HttpResponseMessage PutVideoAdvertise(VideoUpload video)
        {
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }

            if (db.AddNewMedia(video.AdvId, video.MediaLink) != 0)
            {
                return Request.CreateResponse(HttpStatusCode.OK, video);
            }
            else
            {
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Not Found");
            }
        }

        /// <summary>
        /// Get access token for youtube upload video
        /// </summary>
        /// <returns></returns>
        public FormUploadToken GetYoutubeAccessToken()
        {
            var queryString = HttpUtility.ParseQueryString(Request.RequestUri.Query);
            var title = DateTime.Now.Date.ToShortDateString() + queryString["Title"];
            YouTubeRequestSettings settings = new YouTubeRequestSettings("youtubeTest", "AIzaSyCyunCesXcmbQbggwaP1oJBs-R17SyLiZM", "hoangvx1102@gmail.com", "mmhbntmbhm92KS");
            YouTubeRequest request = new YouTubeRequest(settings);
            Video newVideo = new Video();
            newVideo.Title = title;
            newVideo.Tags.Add(new MediaCategory("Entertainment", YouTubeNameTable.CategorySchema));
            newVideo.Description = "Tebbee co. Advertisement";
            newVideo.YouTubeEntry.Private = false;
            FormUploadToken token = request.CreateFormUploadToken(newVideo);
            return token;
        }

        /// <summary>
        /// Get list comment of an ad.
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public IEnumerable<Comment_GetByAdv_Result> GetCommentsByAdv(int id)
        {
            var comments = db.GetCommentsByAdv(id);
            return comments;
        }

        public HttpResponseMessage PutComment(Tebbee.UI.Client.AdvertiseSer.Comment cm)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
                }
                var resutl = db.EditComment(cm);
                if (resutl != 0)
                {
                    return Request.CreateResponse(HttpStatusCode.OK, cm);
                }
                else
                {
                    return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Not Found");
                }
            }
            catch (Exception ex)
            {
                throw new ApplicationException(ex.Message, ex);
            }
        }
    }

    /// <summary>
    /// class to get data when update video link
    /// </summary>
    public class VideoUpload
    {
        public int AdvId { get; set; }
        public String MediaLink { get; set; }
    }
}
